package com.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.forum.mapper.*;
import com.forum.pojo.*;
import com.forum.pojo.vo.ChildCommentVo;
import com.forum.pojo.vo.ForumCommentVo;
import com.forum.pojo.vo.UserCommentVo;
import com.forum.pojo.vo.ForumModify;
import com.forum.result.Result;
import com.forum.service.ForumCommentService;
import com.forum.service.StudentInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
* @author 86152
* @description 针对表【forum_comment(评论)】的数据库操作Service实现
* @createDate 2023-01-31 00:42:33
*/
@Service
public class ForumCommentServiceImpl extends ServiceImpl<ForumCommentMapper, ForumComment>
    implements ForumCommentService{
    @Autowired
    ForumCommentMapper forumCommentMapper;
    @Autowired
    ForumArticleMapper forumArticleMapper;
    @Autowired
    UserMessageMapper userMessageMapper;
    @Autowired
    StudentInfoMapper studentInfoMapper;
    @Autowired
    TeacherInfoMapper teacherInfoMapper;
    @Override
    public List loadComments(String articleId) {
        List<Map<String,Object>> results=new ArrayList<>();
        List<ForumComment> forumComments = this.getAllFirstComments(articleId);
        for (ForumComment forumComment:forumComments) {
            Map<String,Object> param=new HashMap<>();
            Integer pid=forumComment.getCommentId();
            QueryWrapper<ForumComment> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("p_comment_id",pid);
            List<ForumComment> childComments= forumCommentMapper.selectList(queryWrapper);
            List<ChildCommentVo> childCommentVos=new ArrayList<>();
            for (ForumComment childComment:childComments) {
                ChildCommentVo childCommentVo=new ChildCommentVo();
                QueryWrapper child1=new QueryWrapper();
                QueryWrapper child2=new QueryWrapper();
                child1.eq("studentId",childComment.getUserId());
                child2.eq("teacherId",childComment.getUserId());
                StudentInfo student=studentInfoMapper.selectOne(child1);
                TeacherInfo teacher=teacherInfoMapper.selectOne(child2);
                childCommentVo.setForumComment(childComment);
                if(student!=null){
                    childCommentVo.setAvartUrl(student.getAvartarurl());
                    childCommentVo.setIdentity(student.getIdentity());
                }else if(teacher!=null){
                    childCommentVo.setAvartUrl(teacher.getAvartarurl());
                    childCommentVo.setIdentity("1");
                }
                childCommentVos.add(childCommentVo);
            }
            QueryWrapper queryWrapper1=new QueryWrapper();
            queryWrapper1.eq("studentId",forumComment.getUserId());
            QueryWrapper queryWrapper2=new QueryWrapper();
            queryWrapper2.eq("teacherId",forumComment.getUserId());
            StudentInfo studentInfo = studentInfoMapper.selectOne(queryWrapper1);
            TeacherInfo teacherInfo = teacherInfoMapper.selectOne(queryWrapper2);
            if(studentInfo!=null){
                param.put("avartUrl",studentInfo.getAvartarurl());
                param.put("identity",studentInfo.getIdentity());
            }else if(teacherInfo!=null){
                param.put("avartUrl",teacherInfo.getAvartarurl());
                param.put("identity",teacherInfo.getIdentity());
            }
            param.put("comment",forumComment);
            param.put("childComments",childCommentVos);
            results.add(param);
        }
        return results;
    }

    @Override
    public void addComment(Long replyUserId, ForumCommentVo forumCommentVo, Long userId) {
        Date date = new Date();
        UserMessage userMessage = new UserMessage();
        userMessage.setCreateTime(date);
        ForumComment forumComment=new ForumComment();
        forumComment.setUserId(userId);
        String name = forumArticleMapper.findNickNameByUserId(userId);
        forumComment.setNickName(name);
        if(replyUserId!=null){
            forumComment.setpCommentId(forumCommentVo.getpCommentId());
            forumComment.setArticleId(forumCommentVo.getArticleId());
            forumComment.setContent(forumCommentVo.getContent());
            forumComment.setPostTime(date);
            forumComment.setGoodCount(0);
            forumComment.setReplyUserId(replyUserId);
            QueryWrapper queryWrapper1=new QueryWrapper();
            queryWrapper1.eq("studentId",replyUserId);
            QueryWrapper queryWrapper2=new QueryWrapper();
            queryWrapper2.eq("teacherId",replyUserId);
            StudentInfo studentInfo = studentInfoMapper.selectOne(queryWrapper1);
            TeacherInfo teacherInfo = teacherInfoMapper.selectOne(queryWrapper2);
            if(studentInfo!=null){
                forumComment.setReplyNickName(studentInfo.getNickname());
            }else{
                forumComment.setReplyNickName(teacherInfo.getNickname());
            }
            forumComment.setStatus(0);
            forumComment.setTopType(0);
        }else {
            if (forumCommentVo.getpCommentId().equals(0)) {
                forumComment.setpCommentId(0);
                forumComment.setArticleId(forumCommentVo.getArticleId());
                forumComment.setContent(forumCommentVo.getContent());
                forumComment.setPostTime(date);
                forumComment.setGoodCount(0);
                forumComment.setStatus(0);
                forumComment.setTopType(0);
            } else {
                forumComment.setpCommentId(forumCommentVo.getpCommentId());
                forumComment.setArticleId(forumCommentVo.getArticleId());
                forumComment.setContent(forumCommentVo.getContent());
                forumComment.setPostTime(date);
                forumComment.setGoodCount(0);
                Integer pid = forumCommentVo.getpCommentId();
                QueryWrapper<ForumComment> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("comment_id", pid);
                ForumComment comment = forumCommentMapper.selectOne(queryWrapper);
                forumComment.setReplyUserId(comment.getUserId());
                forumComment.setReplyNickName(comment.getNickName());
                forumComment.setStatus(0);
                forumComment.setTopType(0);
            }
        }
        userMessage.setSendUserId(userId);
        userMessage.setMessageType(1);
        userMessage.setMessageContent(forumCommentVo.getContent());
        userMessage.setStatus(0);
        userMessage.setSendNickName(name);
        userMessage.setArticleId(forumCommentVo.getArticleId());

        QueryWrapper<ForumArticle> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id",forumCommentVo.getArticleId());
        ForumArticle forumArticle = forumArticleMapper.selectOne(wrapper);
        forumArticle.setCommentCount(forumArticle.getCommentCount()+1);
        forumArticleMapper.updateById(forumArticle);
        userMessage.setArticleTitle(forumArticle.getTitle());
        forumCommentMapper.insert(forumComment);
        userMessage.setCommentId(forumComment.getCommentId());
        userMessage.setReceivedUserId(forumComment.getReplyUserId());
        userMessageMapper.insert(userMessage);
    }

    public Page loadCommentsByPage(String articleId,Integer pageNo, Integer pageSize) {
        List<ForumComment> list=this.loadComments(articleId);
        Page pages = getPages(pageNo, pageSize, list);
        return pages;
    }

    @Override
    public Result getPersonComment(Long userId) {
        QueryWrapper<ForumComment> forumArticleQueryWrapper=new QueryWrapper<>();
        forumArticleQueryWrapper.eq("user_id",userId);
        List<ForumComment> forumComments = forumCommentMapper.selectList(forumArticleQueryWrapper);
        List<ForumModify> forumModifies=forumCommentPackge(forumComments);
        return Result.ok(forumModifies);
    }

    private List<ForumModify> forumCommentPackge(List<ForumComment> list) {
        ArrayList<ForumModify> forumModifies = new ArrayList<>();
        for(ForumComment listItem:list){
            ForumModify forumModify = new ForumModify();
            forumModify.setForumComment(listItem);
            ForumArticle forumArticle = forumArticleMapper.selectByArticleId(listItem.getArticleId());
            forumModify.setTitle(forumArticle.getTitle());
            forumModify.setSummary(forumArticle.getSummary());
            Long userId = listItem.getUserId();
            forumModify.setAuthorIdentity(forumArticleMapper.selectIdentity(userId));
            forumModifies.add(forumModify);
        }
        return forumModifies;
    }

    @Override
    public Page<UserCommentVo> loadCommentsByUserName(String username, Integer pageNo, Integer pageSize) {
        QueryWrapper<ForumComment> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(username)) {
            queryWrapper.eq("nick_name", username);
        }
        List<ForumComment> forumComments = forumCommentMapper.selectList(queryWrapper);

        List<UserCommentVo> userCommentVos=new ArrayList<>();
        for (ForumComment forumComment:forumComments) {
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("article_id",forumComment.getArticleId());
            UserCommentVo userCommentVo=new UserCommentVo();
            userCommentVo.setUsername(forumComment.getNickName());
            userCommentVo.setCommentId(forumComment.getCommentId());
            userCommentVo.setContent(forumComment.getContent());
            if(forumArticleMapper.selectOne(wrapper)!=null){
                userCommentVo.setTitle(forumArticleMapper.selectOne(wrapper).getTitle());
            }
            userCommentVo.setLike(forumComment.getGoodCount());
            userCommentVo.setPostTime(forumComment.getPostTime());
            userCommentVos.add(userCommentVo);
        }
        return getPages(pageNo,pageSize,userCommentVos);
    }

    @Override
    public int setTop(Integer commentId, Integer type) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("comment_id",commentId);
        ForumArticle forumArticle = forumArticleMapper.selectOne(queryWrapper);
        forumArticle.setTopType(type);
        return forumArticleMapper.updateById(forumArticle);
    }


    public static Page getPages(Integer currentPage, Integer pageSize, List list){

        Page page = new Page();

        int size = list.size();
        if(size==0){
            return null;
        }
        if(pageSize > size){
            pageSize = size;
        }

        //求出最大页数，防止currentPage越界
        int maxPage = size % pageSize == 0 ? (size / pageSize) : (size / pageSize) + 1;

        if(currentPage > maxPage){
            currentPage = maxPage;
        }

        //当前页第一条数据下标
        int curIds = currentPage > 1 ? (currentPage -1) * pageSize : 0;

        List pageList = new ArrayList<>();

        //将当前页的数据放进pageList
        for (int i = 0; i < pageSize && curIds + i < size; i++) {
            pageList.add(list.get(curIds + i));
        }

        page.setCurrent(currentPage).setSize(pageSize).setTotal(list.size()).setRecords(pageList);

        return page;

    }
    private List<ForumComment> getAllFirstCommentsByPage(String articleId) {
        QueryWrapper<ForumComment> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("article_id",articleId);
        queryWrapper.eq("p_comment_id",0);
        return  forumCommentMapper.selectList(queryWrapper);
    }

    public List<ForumComment> getAllFirstComments(String articleId){
        QueryWrapper<ForumComment> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("article_id",articleId);
        queryWrapper.eq("p_comment_id",0);
        return  forumCommentMapper.selectList(queryWrapper);
    }
    @Override
    @Transactional(rollbackFor = {Exception.class}, readOnly = false)
    public boolean deleteByArticleId(Integer commentId) {
        ForumComment forumComment = forumCommentMapper.selectByCommentId(commentId);
        String content = forumComment.getContent();
        Date postTime = forumComment.getPostTime();
        userMessageMapper.deleteByContentAndPostTime(content,postTime);
        return removeById(commentId);
    }
}




